#!/usr/bin/env python

#
# $Id: app_server.py,v 1.1 2003/05/06 19:26:43 bconrad Exp $
#

import SocketServer
import string
import os
import os.path
import re

##############################################################################

class MyHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        app = string.strip(self.rfile.readline(1024))
        app = self.server.find_executable(app)
        
        args = [app]
        arg = string.strip(self.rfile.readline(1024))
        while len(arg) > 0:
            #            arg = os.path.abspath(self.server.map_file(arg))
            arg = self.server.map_file(arg)
            if os.path.exists(arg):
                arg = os.path.normpath(arg)
            args.append('"' + arg + '"')
            arg = string.strip(self.rfile.readline(1024))

        cmd = string.join(args)
        print cmd
        result = os.spawnv(os.P_WAIT, app, args)
        if 0 == result:
            self.wfile.write('OK - ' + string.join(args))
        else:
            self.wfile.write('NOPE - ' + string.join(args))
        
##############################################################################

class MyServer(SocketServer.ThreadingTCPServer):

    def __init__(self, RequestHandlerClass):
        self.command_cache = {}

        self.dir_map = []
        self.read_config()

        SocketServer.TCPServer.__init__(self, (self.host, self.port), RequestHandlerClass)

    def read_config(self):

        default_vars = {}

        if os.environ.has_key('USER'):
            default_vars['user'] = os.environ['USER']
        elif os.environ.has_key('USERNAME'):
            default_vars['user'] = os.environ['USERNAME']
            
        config_dir = os.environ.get('HOME', '')
        config_dir = os.path.join(config_dir, '.app_server')
        config_file = os.path.join(config_dir, 'config')

        import ConfigParser;
        config_parser = ConfigParser.ConfigParser(default_vars)
        try:
            config_parser.read(config_file)
        except ConfigParser.MissingSectionHeaderError, error:
            sys.stderr.write('Warning - config file has no sections.\n')
            
        self.host = config_parser.get('NETWORK', 'host')
        self.port = config_parser.getint('NETWORK', 'port')

        for option in filter(lambda x: string.find(x, 'source_dir_') == 0,
                             config_parser.options('DIR_MAP')):
            value = config_parser.get('DIR_MAP',
                                      string.replace(option,
                                                     'source_dir_',
                                                     'target_dir_',
                                                     1))
            self.dir_map.append((config_parser.get('DIR_MAP', option),
                                 value))

    def map_file(self, file_name):
        for (from_string, to_string) in self.dir_map:
            file_name = re.sub(from_string, to_string, file_name)
#              if string.find(file_name, from_string) == 0:
#                  return string.replace(file_name, from_string, to_string, 1)
        return file_name

    def find_executable(self, exec_name):
        if self.command_cache.has_key(exec_name):
            return self.command_cache[exec_name]
        
        path = string.split(os.environ['PATH'], ';')
        extensions = ['']
        extensions.extend(string.split(os.environ['PATHEXT'], ';'))

        for directory in path:
            for extension in extensions:
                full_path = os.path.join(directory, exec_name + extension)
                if os.path.exists(full_path):
                    self.command_cache[exec_name] = full_path
                    return full_path
        print 'couldn\'t find', exec_name
        return exec_name

##############################################################################

if __name__ == '__main__':
    server = MyServer(MyHandler)
    # server.handle_request()
    server.serve_forever()


